// const basicAuth = require("basic-auth");
import basicAuth from "basic-auth"
import jwt from 'jsonwebtoken'

//token中间件检测
export const authenticateToken = (req, res, next) => {
    //登录路径就直接放行
    if (req.path == "/api/user/login" || req.path == "/api/captcha" || req.path == "/api/user/register" || req.path == "/api/user/womai" || req.path == "/api/upload") {
        return next();
    }
    //从请求头获取token
    const auth = req.headers['authorization']
    if (!auth) return res.status(401).send({
        code: 1,
        msg: "没有访问权限"
    })
    const token = auth.split(' ')[1];
    if (!token) return res.status(401).send({
            code: 401,
            msg: "没有访问权限,token不正确"
    })
    const obj = jwt.verify(token, "shn")
    req.username = obj.username;
    try {
        //token合法就放行
        const authcode = jwt.verify(token, "shn");
        console.log(authcode);

        //后续可以进行操作
        next()
    } catch (error) {
        //异常
        if (error.name == "TokenExpiredError") {
            return res.status(401).send({
                code: 401,
                msg: "账号过期,请重新登录"
            })
        } else {
            return res.status(401).send({
                code: 401,
                msg: "没有访问权限3"
            })
        }
    }
}